package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.twu.biblioteca.BiblioMessages.SEPARATOR;

public class BookSystem {
    private Map<String, String> checkedBooks = new HashMap<String, String>();
    private List<Book> books = new ArrayList<Book>();

    public boolean returnBook(String input) {
        try {
            String[] params = input.split(SEPARATOR);
            String bookName = params[0];
            String userName = params[1];
            if(this.contains(bookName)){
                if(checkedBooks.containsKey(bookName) && userName.equals(checkedBooks.get(bookName))) {
                    checkedBooks.remove(bookName);
                    return true;
                } else {
                    return false;
                }
            }else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public boolean checkout(String input) {
        try {
            String[] params = input.split(SEPARATOR);
            String bookName = params[0];
            String userName = params[1];
            if(contains(bookName)){
                if(!checkedBooks.containsKey(bookName)) {
                    checkedBooks.put(bookName, userName);
                    return true;
                } else {
                    return false;
                }
            }else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public void add(Book book) {
        books.add(book);
    }

    public String listBooks() {
        StringBuilder sb = new StringBuilder();
        sb.append(BiblioMessages.BOOK_LIST);
        for (Book book : books) {
            sb.append("\n").append(book.name());
        }
        return sb.toString();
    }

    public boolean contains(String name) {
        for (Book book : books) {
            if(name.equals(book.name())){
                return true;
            }
        }
        return false;
    }

}
